<?php

// +----------------------------------------------------------------------
// | WeiPHP [ 公众号和小程序运营管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://www.weiphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 凡星 <weiphp@weiphp.cn> <QQ:203163051>
// +----------------------------------------------------------------------
namespace app\common\controller;

use think\Controller;
use think\facade\Log;

/**
 * PC运营管理端的控制器基类，实现PC版的初始化，权限控制和一些通用方法
 *
 * @author 凡星
 *
 */
class WebBase extends Controller
{

    protected $top_more_button = [];

    public function __construct()
    {
        header('Access-Control-Allow-Origin:*');
        // 响应类型
        header('Access-Control-Allow-Methods:*');
        // 响应头设置
        header('Access-Control-Allow-Headers:x-requested-with,content-type');
        
        // WeiPHP常量定义
        defined('MODULE_NAME') or define('MODULE_NAME', request()->module());
        defined('CONTROLLER_NAME') or define('CONTROLLER_NAME', request()->controller());
        defined('ACTION_NAME') or define('ACTION_NAME', request()->action(true));
        
        
        defined('NOW_TIME') or define('NOW_TIME', $_SERVER['REQUEST_TIME']);
        defined('IS_GET') or define('IS_GET', request()->isGet());
        defined('IS_POST') or define('IS_POST', request()->isPost());
        defined('IS_AJAX') or define('IS_AJAX', request()->isAjax());
        
        $url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
        defined('__SELF__') or define('__SELF__', strip_tags($url));
        
        $requestData = input();
        $requestData = empty($requestData) ? [] : $requestData;
        $_REQUEST = array_merge($_REQUEST, $requestData);
        //         add_debug_log($_REQUEST, 'testvistisf_'.get_mid());
        if (isset($_REQUEST['PHPSESSID']) && !empty($_REQUEST['PHPSESSID'])) {
            //             session_id($_REQUEST['PHPSESSID']);
        }
        //         add_debug_log($_SESSION, 'testvistisf11_'.get_mid());
        
        // 不用记录定时任务的日志
        if (ACTION_NAME != 'cron' && CONTROLLER_NAME != 'Canal' && CONTROLLER_NAME != 'Cron') {
            Log::key('allow_log');
        } else {
            Log::key('fobi_log');
        }
        // 解决TP框架中的GET不包含PHP_INFO里的参数的问题
        $route = input('route.');
        $_GET = array_merge($route, $_GET);
        
        
        $public_dir = parse_name(MODULE_NAME);
         
        if (!is_dir(SITE_PATH . '/public/assets/' . $public_dir)) {
            $public_dir = 'home';
        }

        config('template.tpl_replace_string', array(
            '__STATIC__' => __ROOT__ . '/assets/plugins',
            '__IMG__' => __ROOT__ . '/assets/' . $public_dir . '/images',
            '__CSS__' => __ROOT__ . '/assets/' . $public_dir . '/css',
            '__JS__' => __ROOT__ . '/assets/' . $public_dir . '/js',
            '__ROOT__' => __ROOT__, // 当前网站地址
            '__SELF__' => __SELF__, // 当前页面地址
            '__PUBLIC__' => __ROOT__,
            '__PUBLICTHIS__' => __ROOT__ . '/' . $public_dir
        )); // 站点公共目录
        
        parent::__construct();
    }

    function initialize()
    {
        parent::initialize();
    
        if (strtolower(MODULE_NAME) != 'install') {
    
        }
    }
    

    // 通用插件的列表模型
    public function lists()
    {
        $model = I('model');
        $model = $this->getModel($model);
        $templateFile = $this->getAddonTemplate($model['template_list']);

        return $this->common_lists($model, $templateFile);
    }

    public function export()
    {
        $model = I('model');
        $model = $this->getModel($model);
        $this->common_export($model);
    }

    // 通用插件的编辑模型
    public function edit()
    {
        $model = I('model');
        $id = I('id');
        $model = $this->getModel($model);
        $templateFile = $this->getAddonTemplate($model['template_edit']);
        return $this->common_edit($model, $id, $templateFile);
    }

    // 通用插件的增加模型
    public function add()
    {
        $model = I('model');
        $model = $this->getModel($model);
        $templateFile = $this->getAddonTemplate($model['template_add']);

        return $this->common_add($model, $templateFile);
    }

    // 通用插件的删除模型
    public function del()
    {
        $model = I('model');
        $ids = I('ids');
        return $this->common_del($model, $ids);
    }

    // 通用设置插件模型
    public function config()
    {
        $map['name'] = parse_name(MODULE_NAME, 0);
        $controller = parse_name(CONTROLLER_NAME, 0);

        $pkey = $map['name'] . '_' . $controller;

        $addon = [];

        $file = env('app_path') . $map['name'] . '/config.php';

        $re_arr = include $file;

        $addon = isset($re_arr[$controller]) ? $re_arr[$controller] : $re_arr;

        if (request()->isPost()) {
            $data = input('post.');
            foreach ($addon as $k => $vv) {
                if ($vv['type'] == 'material') {
                    $type_name = input('post.material_' . $k . '_type');
                    $final_value = $type_name . ':' . input('post.material_' . $k . '_' . $type_name . '_id');

                    $data[$k] = $final_value;
                }
            }
            // dump(input('post.'));exit;
            $flag = D('common/PublicConfig')->setConfig($pkey, $data);

            if ($flag !== false) {
                $this->success('保存成功');
            } else {
                $this->error('保存失败');
            }
        }

        $db_config = D('common/PublicConfig')->getConfig($map['name'], $pkey);
        // dump($db_config);
        if (!empty($db_config)) {
            foreach ($addon as $key => $value) {
                !isset($db_config[$key]) || $addon[$key]['value'] = $db_config[$key];
            }
        }
        // dump($addon);
        $this->assign('fields', $addon);

        $data = [];
        foreach ($addon as $key => $value) {
            $data[$key] = $value['value'];
        }
        $this->assign('data', $data);

        return $this->fetch();
    }

    // 没有管理页面和配置页面的插件的通用提示页面
    public function nulldeal()
    {
        return $this->fetch('common@base/nulldeal');
    }

    function scene_res($obj, $success = true, $code = 200, $msg = '', $map = null, $list = null)
    {
        $data['obj'] = $obj;
        $data['success'] = $success;
        $data['code'] = $code;
        $data['msg'] = $msg;
        $data['map'] = $map;
        $data['list'] = $list;
        return json($data);
    }

    function scene_json_res($data)
    {
        if (!is_array($data)) {
            $data = json_decode($data, true);
        }
        return json($data);
    }

    function scene_check_loin()
    {
        if (intval(session('mid_' . get_pbid())) == 0) {
            header('Content-type: text/json');
            header('HTTP/1.1 401 error');
            echo json_encode(array(
                "success" => false,
                "code" => 1001,
                "msg" => "请先登录!",
                "obj" => null,
                "map" => null,
                "list" => null
            ));
            exit();
        }
    }
}
